package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        先判断是否访问登录界面
//        1.先拿出访问的url
        URI uri = exchange.getRequest().getURI();
        if (uri.getPath().contains("/login")){
            return chain.filter(exchange);
        }
//        如果不是访问登录页面，就获取request的token
        String token = exchange.getRequest().getHeaders().getFirst("token");

        if (!StringUtils.isEmpty(token)){
//            解析token
            try {


                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                int i = AppJwtUtil.verifyToken(claimsBody);
                if (i == 1 || i == 2){
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                    return exchange.getResponse().setComplete();
                }
                else if (i == -1 || i ==0){
                    //在header中添加新信息,相当于再给tokne做解析
                    ServerHttpRequest request = exchange.getRequest();
                    ServerHttpResponse response = exchange.getResponse();
                    Object userid = claimsBody.get("id");
                    ServerHttpRequest newrequest = request.mutate().headers(httpHeaders -> {
                        httpHeaders.add("userId", userid + "");
                    }).build();

                    exchange.mutate().request(newrequest).build();
    //                token有效,没有过期,放行
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                e.printStackTrace();
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }

        }
          //token为空
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
